import hashlib
import json
import os
import string
from random import random
from typing import Dict, Optional
from urllib.request import Request

import requests
from fastapi import FastAPI, HTTPException, Depends, Header
from fastapi.logger import logger
from pydantic import BaseModel

from db.search_record import SearchRecordService
from db.user import UserAuthService
from dy_apis.douyin_api import DouyinAPI
from main import Data_Spider
from utils.RequestTools import LoginRequest, RegisterRequest
from utils.common_util import init
from utils.data_util import handle_work_info

# 创建 FastAPI 应用实例
app = FastAPI()
douyin_apis = DouyinAPI()
auth, base_path = init()
data_spider = Data_Spider()
userAuthService = UserAuthService()
searchService = SearchRecordService()

# 从环境变量读取JWT密钥
JWT_SECRET = os.getenv("JWT_SECRET")
JWT_ALGORITHM = "HS256"

# 定义简单的 GET 接口
@app.get("/douyin/search")
async def search(query: str,
                 require_num : int = 20,
                 sort_type : str = '2',
                 publish_time : str = '0',
                 filter_duration : str = '0',
                 search_range : str = "0",
                 content_type : str = "1",
                 authorization: Optional[str] = Header(None)
                 ):

    # # 3 搜索指定关键词的作品
    # query = "美女"
    # require_num = 30  # 搜索的数量
    # sort_type = '2'  # 排序方式 0 综合排序, 1 最多点赞, 2 最新发布
    # publish_time = '0'  # 发布时间 0 不限, 1 一天内, 7 一周内, 180 半年内
    # filter_duration = ""  # 视频时长 空字符串 不限, 0-1 一分钟内, 1-5 1-5分钟内, 5-10000 5分钟以上
    # search_range = "0"  # 搜索范围 0 不限, 1 最近看过, 2 还未看过, 3 关注的人
    # content_type = "1"  # 内容形式 0 不限, 1 视频, 2 图文
    if not authorization:
        raise HTTPException(status_code=401, detail="缺少授权信息")
    token = authorization.split(" ")[1]
    current_user = userAuthService.verify_token(token)
    if not current_user:
        raise HTTPException(401,"请先登陆")
    print(current_user)
    record = searchService.add_search_record(query,0,current_user["user_id"])
    print("record=", record)
    work_list = douyin_apis.search_some_general_work(auth, query, require_num, sort_type, publish_time,
                                                          filter_duration, search_range, content_type)
    if 200 == record['code']:
        id_value = record['id']
        searchService.update_search_record(len(work_list), id_value)
    else:
        print("添加搜索记录失败")
        # 处理键不存在的情况，例如跳过更新或记录日志

    return {"code": "200", "data": work_list}


@app.get("/douyin/comments")
async def work_comments(url : str,authorization: str = Header(None)):
    if not authorization:
        raise HTTPException(status_code=401, detail="缺少授权信息")
    print("authorization=",authorization)
    token = authorization.split(" ")[1]
    print("token=",token)
    res = userAuthService.verify_token(token)
    print(res)
    comments = douyin_apis.get_work_out_comment(auth, url)
    return comments


@app.post("/douyin/login")
async def login(login_data: LoginRequest):

    return userAuthService.user_login(login_data)

@app.post("/douyin/register")
async def login(register_data: RegisterRequest):

    return userAuthService.user_register(register_data)




